package com.fakeDYChat.common.common.event.listener;

import com.fakeDYChat.common.common.event.UserBlackEvent;
import com.fakeDYChat.common.common.event.UserOnlineEvent;
import com.fakeDYChat.common.user.dao.UserDao;
import com.fakeDYChat.common.user.domain.entity.User;
import com.fakeDYChat.common.user.domain.entity.UserBackpack;
import com.fakeDYChat.common.user.domain.enums.ActiveStatusEnum;
import com.fakeDYChat.common.user.service.IpService;
import com.fakeDYChat.common.user.service.cache.UserCache;
import com.fakeDYChat.common.websocket.domain.vo.resp.WSBaseResp;
import com.fakeDYChat.common.websocket.service.WebSocketService;
import com.fakeDYChat.common.websocket.service.adapter.WSAdapter;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Service
public class UserBlackListener {

    private final WebSocketService webSocketService;
    private final UserDao userDao;
    private final UserCache userCache;

    public UserBlackListener(WebSocketService webSocketService, UserDao userDao, UserCache userCache) {
        this.webSocketService = webSocketService;
        this.userDao = userDao;
        this.userCache = userCache;
    }

    /**
     * 推送拉黑消息
     *
     * @param userBlackEvent 用户拉黑事件
     * @author Tang
     * @date 2024/1/4 16:11
     **/
    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void sendMsg(UserBlackEvent userBlackEvent) {
        User user = userBlackEvent.getUser();
        webSocketService.sendMsgToAll(WSAdapter.buildBlack(user));
    }

    /**
     * 将用户更新为拉黑态
     *
     * @param userBlackEvent 用户拉黑事件
     * @author Tang
     * @date 2024/1/12 21:12
     **/
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent userBlackEvent) {
        User user = userBlackEvent.getUser();
        Long userId = user.getId();
        userDao.blackUserByUid(userId);
    }

    /**
     * 清空黑名单缓存
     *
     * @param userBlackEvent 用户拉黑事件
     * @author Tang
     * @date 2024/1/12 21:12
     **/
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void clearBlackMap(UserBlackEvent userBlackEvent) {
        userCache.evictBlackMap();
    }
}
